
import defaultSettings from "@/config/defaultSettings"
import {filterDictText,StringToJson,isJSON} from '@/utils/util'
import {initDict} from "@/api/dict"
import request from '@/utils/request'
import pageSetting from "@/components/lt/codeGenerator/pageSetting"
import { Modal } from 'ant-design-vue'
import Vue from 'vue'
import { v4 as uuidv4 } from 'uuid'
import SnowflakeId from 'snowflake-id'

export const SysMixin = {
    data(){
        return {
            initDictIsFinish:true,
            initDictCodes:null,
            that:this,
            dictTextInfo:this.$store.state.dict.dictTextInfo,
            pageMap:new Map(),
            snowflake: new SnowflakeId(),

        }
    },
    created(){
        this.initDict()
    },
    mounted() {
       
    },
    watch:{
        initDictCodes(newVal,oldVal){
            if(newVal){
                this.initDict()
            }
            
        }
    },
    beforeDestroy(){
        this.$bus.clear(this)
    },
    methods:{
       
        dictText(dictCode,val){
            if(!val){
                return ''
            }
            let that = this
            let key = dictCode+'#'+val
            if(that.initDictIsFinish){
                if(that.dictTextInfo[key]){
                    return that.dictTextInfo[key]
                }
                if(that.$store.state.dict.dictInfo[dictCode]){
                 
                    let text = filterDictText(that.$store.state.dict.dictInfo[dictCode].dictInfo,val+"")
                    that.$store.dispatch("setDictTextInfo",{key:key,val:text})
                    return text
                }
                return val
            }else{
                return val
            }
            
        },
        initDict(){
            
            if(this.initDictCodes){
                this.initDictIsFinish=false
                initDict(this.initDictCodes,'').then(() => {
                    this.initDictIsFinish=true
                }) 
            }
        },
        handleEdit (record,ref,title) {
            this.$refs[ref].edit(record);
            this.$refs[ref].title =title;
            this.$refs[ref].disableSubmit = false
        },
        
        handleDelete(params,delUrl,ref){
            if(!delUrl){
                this.$message.error("请设置删除地址!")
                return
            }
   
            var that = this;
            request.get(delUrl,{params:params}).then((res)=>{
                if (res.success) {
                    that.$message.success(res.message);
                    that.refresh(ref);
                } else {
                    that.$message.warning(res.message);
                }
            })

        },
       
        refresh(tabRef){
            this.$refs[tabRef].refresh()
        },
        refreshData(tabRef){
            this.$refs[tabRef].refreshData()
        },
        editTableCustomRow(record,tabRef){
            let dataList = this.$refs[tabRef].localDataSource
            for(let i=0;i<dataList.length;i++){
                if(dataList[i].keyId==record.keyId){
                    dataList[i][defaultSettings.常量.表格是否可编辑属性] = true
                }else{
                    dataList[i][defaultSettings.常量.表格是否可编辑属性] = false
                }
            }
                       
            // console.log(this.$refs[tabRef].localDataSource)
            this.$refs[tabRef].refreshData()
        },
        
        findByRef (context, ref) {
            const childrens = context.$children;
            let children = null
            if (childrens.length) {
                    for (const child of childrens) {
                        if(ref in child.$refs){
                            children = child
                            break
                    } else {
                        children = this.findByRef(child, ref)
                        if (children) break
                    }
                }
            }
            return children
        },
        // findComponentDownward (context, componentName) {
        //     const childrens = context.$children;
        //     let children = null;
          
        //     if (childrens.length) {
        //       for (const child of childrens) {
        //         const name = child.$options.name;
          
        //         if (name === componentName) {
        //           children = child;
        //           break;
        //         } else {
        //           children = this.findComponentDownward(child, componentName);
        //           if (children) break;
        //         }
        //       }
        //     }
        //     return children;
        //   },
        //弹出页面的回到函数
        closeCallback(arg){
            if(typeof(arg) == "string" && arg.constructor === String && Object.prototype.toString.call( arg) == "[object String]"){
                let refArr = arg.split(',')
                for(let ref of refArr){
                    this.tableRefresh(ref)
                }
                
            }else if(arg["method"]){
                this[arg["method"]](arg)
            }else{
                this.callBack(arg)
            }
        },
        callBack(arg){},
        tableRefresh(ref){
            if(!ref){
                return false
            }
            let table = this.findByRef(this,ref) || this.$refs[ref]
            if(!table){
               return false 
            }
            table.refresh()
        },
        tableDel(params,delUrl,ref){
            if(!delUrl){
                this.$message.error("请设置删除地址!")
                return
            }
            var that = this;
            Modal.confirm({
                title: "系统提醒",
                content: "确定删除吗?",
                onOk: () => {
                    request.get(delUrl,{params:params}).then((res)=>{
                        if (res.success) {
                            that.$message.success(res.message);
                            that.tableRefresh(ref);
                        } else {
                            that.$message.warning(res.message);
                        }
                    })
                },
                onCancel () {}
            })

        },
        tableInputCellChange(e,record,field){
            let value
            if(e.target && e.target){
                value = e.target.value
            }else{
                value = e
            }
            record[field]=value
        },
        excelUploadCallBack(){},
        excelDownCallBack(){},
        uuid(){
            return uuidv4()
        },
        snowId(){
            return this.snowflake.generate()
        },

        // findComponentUpwardByRef (context, ref) {
        //     const parent = context.$parent
        //     if(parent){
        //         if(ref in parent.$refs){
        //             return parent
        //         }
        //         this.findComponentUpwardByRef(parent,ref)
        //     }
        
        //     return null
        // },
        

        //自定义页面使用的方法开始

        /**
         * 页面打开
         * @param {*} pageId 
         * @param {*} record 
         * @param {*} ref 
         * @param {*} title 
         */
        sysPageOpen (pageId,record,ref,title) {
            this.$refs[ref].edit(pageId,record)
            this.$refs[ref].title =title;
            this.$refs[ref].disableSubmit = false
        },
        

        //设置表格的操作
        setTableAction(text,record,item,h){
            let actionComponent = []
            item.action.map(a=>{
                actionComponent.push(this.$createElement('a',{on:{click:()=>{this[a.actionMethod](record)}},ref:record[item.props['rowKey']]+"_"+a.actionMethod,attrs:{name:record[item.props['rowKey']]+"_"+a.actionMethod}},a.actionName))
                actionComponent.push(this.$createElement('a-divider',{props:{type:'vertical'}}))
            })
            if(actionComponent.length>0){
               actionComponent = actionComponent.slice(0,-1)
            }
            return actionComponent
        },
        initSysPageComponents(h,components,dictCodes) {
            return(
                components.map(item=>{
                    if(pageSetting.常量.组件.网格表单==item.component){
                        return h(item.component,{props:item.props||{},on:{'changeEventHandler':this.changeEventHandler,'clickEventHandler':this.clickEventHandler}},[this.initSysPageComponents(h,item["components"],dictCodes)])
                    }else if(pageSetting.常量.组件.表单==item.component){
                        return h(item.component,{props:item.props||{},on:{'changeEventHandler':this.changeEventHandler,'clickEventHandler':this.clickEventHandler}})
                    }else if(pageSetting.常量.组件.查询表单==item.component){
                        return h(item.component,{props:item.props||{},on:{'changeEventHandler':this.changeEventHandler,'queryEventHandler':this.queryEventHandler}})
                    }else if(pageSetting.常量.组件.表格==item["component"]){
                        // debugger
                        let editable = false
                        let scopedSlots = {}
                        if(item.props["rowSelection"] && isJSON(item.props["rowSelection"])){
                            item.props["rowSelection"] = StringToJson(item.props["rowSelection"])
                            
                        }
                        item.props.columns.map(c=>{
                            if(c["customFormat"]){
                                //自定义渲染函数
                                c["customRender"] = (text,record,index)=>{
                                    try {
                                        let f= new Function('text,record,index,h',c['customFormat']).bind(this)
                                        return f(text,record,index,h)
                                    } catch (error) {
                                        console.log(error)
                                        return text
                                    }
                                   
                                }
                            }else if(c["scopedSlots"] && c["scopedSlots"]["customRender"]){
                                if(c["editable"]){
                                    editable = true
                                    scopedSlots[c["scopedSlots"]["customRender"]]=(text,record,index)=>{
                                        return this.$createElement('LEditTableColumn',{props:{record:record,index:index,text:text,column:c,table:this.findByRef(this,item.ref),rowKey:item.props["rowKey"]}, ref:record[item.props['rowKey']]+"_"+c["dataIndex"],attrs:{name:record[item.props['rowKey']]+"_"+c["dataIndex"]}})
                                    } 
                                }else if(c["dictCode"]){
                                    //如果是下拉
                                    scopedSlots[c["scopedSlots"]["customRender"]]=(text,record)=>{
                                        return this.dictText(c["dictCode"],text)
                                    }
                                }else if(c["scopedSlots"]["customRender"]==pageSetting.常量.表格操作的插槽名){
                                    scopedSlots[c["scopedSlots"]["customRender"]]=(text,record) => this.$createElement('span',{ref:record[item.props['rowKey']]+"_action",attrs:{name:record[item.props['rowKey']]+"_action"}},this.setTableAction(text,record,item,h))
                                }else if(c["scopedSlots"]["customRender"]==pageSetting.常量.表格行号的属性名){
                                    //行号
                                    scopedSlots[c["scopedSlots"]["customRender"]]=(t,r,index) => {return parseInt(index)+1}
                                }
                            }
    
                        })
                        if(editable){
                            //设置需要初始化的下拉，因为可编辑表格必须保障用到的下拉存在
                            item.props["initDictCodes"] = dictCodes
                        }
                        return h(item.component,{props:item.props||{},scopedSlots:scopedSlots,
                            on:{
                                'onQueryFormChange':this.onQueryFormChange,
                                [`${item.props['rowSelection'] && item.props['rowSelection']["onChange"] || ''}`]:(selectedRowKeys, selectedRows)=>{
                                    if(this[item.props['rowSelection']["onChange"]]){
                                        this[item.props['rowSelection']["onChange"]](selectedRowKeys, selectedRows)
                                    }
                                }
                            }},)
                    }else if(pageSetting.常量.组件.树==item.component){
                        
                        return h(item.component,{props:item.props||{},
                            on:{[`${item.props['treeSelect'] || ''}`]:(node)=>{
                                    if(this[item.props['treeSelect']]){
                                        this[item.props['treeSelect']](node)
                                    }
                                },[`${item.props['treeCheck'] || ''}`]:(checked)=>{
                                    if(this[item.props['treeCheck']]){
                                        this[item.props['treeCheck']](checked)
                                    }
                                }
                            }
                        })
                    }else if(pageSetting.常量.组件.按钮==item.component){
                        if(item.props.dropDownButton){
                            return this.$createElement("ExtDropDownButton",{props:item.props||{},
                                on:{
                                    click:(e)=>{
                                        if(this[item.props['click']]){
                                            this[item.props['click']](e)
                                        }
                                    }
                                },ref:item.ref,
                            },[])
                        }else{
                            return this.$createElement(item.component,{props:item.props||{},
                                on:{
                                    click:()=>{
                                        if(this[item.props['click']]){
                                            this[item.props['click']]()
                                        }
                                    }
                                },
                                ref:item.ref,
                            },[item.props["title"] || "按钮"])
                        }
                        
                    }else if(pageSetting.常量.组件.div==item.component){
                        let style=''
                        if(item["style"]){
                            style = item["style"].replace(/\n/g,'').replace(/\t/g,'').replace(/\r/g,'')
                        }
                        return h(item.component,{style:style},[this.initSysPageComponents(h,item["components"],dictCodes)])
                    }else if(pageSetting.常量.组件.页签==item.component){
                        return h(item.component,{props:item.props||{},key:item.props["key"]?item.props["key"]:item.id,},[this.initSysPageComponents(h,item["components"],dictCodes)])
                    }else if(pageSetting.常量.组件.标签页==item.component){
                        return h(item.component,{
                            props:item.props||{},key:item.props["key"]?item.props["key"]:item.id,
                            on:{
                                change:(key)=>{
                                    if(this[item.props['change']]){
                                        this[item.props['change']](key)
                                    }
                                } 
                            }
                        },[this.initSysPageComponents(h,item["components"],dictCodes)])
                    }else if(pageSetting.常量.组件.按钮组==item.component){
                        return h(item.component,{props:item.props||{},ref:item.ref},[this.initSysPageComponents(h,item["components"],dictCodes)])
                    }else if(item.component.indexOf("Char")>=0 || pageSetting.常量.组件.地图==item.component){
                        item.props["pageObject"] = this
                        return h(item.component,{props:item.props||{}})
                    }

                    if(item["components"]&& item["components"].length>0){
                        return h(item.component,{props:item.props||{}},[this.initSysPageComponents(h,item["components"],dictCodes)])
                    }else{
                        return h(item.component,{props:item.props||{}})
                    }
                })
                
            )
        },
        initSysPageData(pageData){
            if(pageData){
                pageData = JSON.parse(pageData)
                for (let key in pageData) {
                    this[key] = pageData[key]
                }
            }
        },
        initSysPageMethods(pageMethods){
            if(pageMethods){
                pageMethods = JSON.parse(pageMethods)
                for (let key in pageMethods) {
                    this[key] =  new Function(pageMethods[key]['arg'],pageMethods[key]['body']).bind(this)
                    
                }
            }
        },
        changeEventHandler(changeItem,method){
            if(method){
                this[method](changeItem)
            }
            this.$emit('changeEventHandler',changeItem)
        },
        
        clickEventHandler(field,form){
            this.$emit('clickEventHandler',field,form)
        },
        onQueryFormChange(changeItem){},

        //queryform查询
        queryEventHandler(val,method){
            if(method){
                this[method](val)
            }
            this.$emit('queryEventHandler',val)
        },
        //自定义页面使用的方法结束
    }
}